import React, { Component } from 'react';
import { Upload, Icon, Modal } from 'antd'
import './index.scss'
import session from '../../utils/Session'

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

class myClass extends Component {
    state = {
        previewVisible: false,
        previewImage: '',
        fileList: [],
        uploadNum:1,//默认最大上传数量是1
        httpUrl:process.env.Text[3]
    };

    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
        });
    };

    handleChange = ({ fileList }) => {
        console.log(22222,fileList)
        if(fileList.length > 0){
            fileList.forEach((e) => {
                if(!(typeof e.url == "string") && e.response){
                    e.url = e.response.data.fullPath;                    
                }
            })
        }
        this.props.onChangeImg(fileList);
    };

    render() {
        const { previewVisible, previewImage, fileList, uploadNum } = this.state;
        
        let _uploadNum = this.props.uploadNum ? this.props.uploadNum : uploadNum;
        let _fileList =  this.props.fileList ? this.props.fileList : fileList;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        // const u = process.env.Text[0];
        return (
            <div className="clearfix">
                <Upload
                    action={this.state.httpUrl + "/center/file/upload"}
                    listType="picture-card"
                    accept=".jpg, .jpeg, .png"
                    headers={{'authorization': sessionStorage.getItem('token'),version:process.env.Text[5]}}
                    fileList={_fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                >
                    {_fileList.length >= _uploadNum ? null : uploadButton}
                </Upload>
                <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
}
export default myClass;